<?php

#namespace humhub\modules\space\controllers;
namespace humhub\modules\api\controllers;

use Yii;
use humhub\modules\space\models\Space;
use humhub\modules\user\models\User;
use humhub\modules\user\widgets\UserListBox;
use humhub\modules\space\models\Setting;
use humhub\modules\content\models\Content;
use humhub\modules\post\models\Post;
use humhub\modules\space\models\Membership;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
#use yii\filters\auth\HttpBasicAuth;
#use yii\filters\auth\QueryParamAuth;

/**
 * 获取Space的内容流, 被关注的用户列表, 指定Space的名称, 关注(取消), 成员数, 头像, 以及用户和Space之间的关系等...
 */
class SpaceController extends Base2Controller
{

    /**
     * @inheritdoc
     */
    public function init(){
        $_GET['sguid'] = Yii::$app->request->get('s');
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
            'guestAllowedActions' => ['stream']
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['update'], $actions['create'], $actions['index'], $actions['delete']);
        return $actions;

        return array(
            'stream' => array(
                'class' => \humhub\modules\content\components\actions\ContentContainerStream::className(),
                'contentContainer' => $this->contentContainer
            ),
        );
    }

    /**
     * 获取指定Space内容列表
     *
     * GET api/space/stream?s=[:guid]&limit=[4]&filters=&sort=c&from=[66]&mode=normal
     *
     * get.s : Space的guid
     *
     * get.limit : 单次获取总量
     *
     * get.from : 起始wallEntryID，默认为空''=第一页
     *
     * @return array  output:返回的内容, counter:表示获取几个wallEntry,  entryIds:表示所有返回的wallEntryID, lastEntryId:列表中最后一个EntryId
     */
    public function actionStream(){
        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        return $stream->run();
    }

    /**
     * 获取单条Post内容(仅限Space中的内容, 如果是任务或课程请查看是否有特定接口)
     *
     * GET api/space/[:wallentryId]
     *
     * :wallentryId = 列表中返回的 wallentryid
     *
     * get.s Post所属用户的sguid
     *
     * @return array  返回的结构同列表
     */
    public function actionView(){
        //基于 Stream 的方式
        if( $_GET['id'] ){
            $_GET['id_wallentryId'] = $_GET['id'];
        }else{
            throw new \yii\web\NotFoundHttpException('Not Found');
        }

        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        return $stream->run();
    }

    /**
     * 获取某板块Space的名称, 关注, 成员数, 头像, 以及用户和Space之间的关系等...
     *
     * GET /api/space/home?s=[guid]
     *
     * get.guid : 板块guid
     *
     * @return array postcount:Posts数量, memberships:成员数量, followercount:被关注数量, spaceimage:板块头像, bannerimage:Banner图, name:板块名称, description:描述, ido:=1可以接受拒绝邀请, =2可以取消申请加入, =3已经是成员, =11可以申请成为成员, =12可以直接成为会员
     */
    public function actionHome(){
        $space = $this->contentContainer;
        $canCreatePosts = $space->permissionManager->can(new \humhub\modules\post\permissions\CreatePost());
        $isMember = $space->isMember();

        $postCount = Content::find()->where([
                    'object_model' => Post::className(),
                    'contentcontainer_id' => $this->space->contentContainerRecord->id,
                ])->count();

        $ido = 0;
        $membership = $space->getMembership();
        if ($membership === null) {
            if ($space->canJoin()) {
                if ($space->join_policy == Space::JOIN_POLICY_APPLICATION) {
                    //申请成为成员
                    $ido = 11;
                } else {
                    //成为会员
                    $ido = 12;
                }
            }
        } elseif ($membership->status == Membership::STATUS_INVITED) {
            //1: 接受/拒绝邀请
            $ido = 1;
        } elseif ($membership->status == Membership::STATUS_APPLICANT) {
            //2: 取消申请加入
            $ido = 2;
        } elseif ( $membership->status == 3 ){
            $ido = 3;
        }

        $user = Array();
        $_user = User::findOne($space->created_by);
        $countTask = Membership::getUserSpaceQuery($_user)
                ->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])
                ->andWhere(['space.created_by' => $_user->id])
                ->andWhere(['space.s_type' => 1])
                ->andWhere(['space.status' => Space::STATUS_ENABLED])
                ->count();
        $countCourse = Membership::getUserSpaceQuery($_user)
                ->andWhere(['!=', 'space.visibility', Space::VISIBILITY_NONE])
                ->andWhere(['space.created_by' => $_user->id])
                ->andWhere(['space.s_type' => 2])
                ->andWhere(['space.status' => Space::STATUS_ENABLED])
                ->count();
        if( $_user ){
            $user['guid']  = $_user->guid;
            $user['image'] = $_user->getProfileImage()->getUrl();
            $user['displayname'] = $_user->displayName;
            $user['title'] = $_user->profile->title;
            $user['u_v']   = $_user->u_v;
            $user['countTask']    = $countTask;
            $user['countCourse']  = $countCourse;
        }

        //member
        $ismember = 0;
        if ($space->isMember()) {
            $ismember = 1;
        }
        return array(
            'postcount' => $postCount,
            'memberships' => $space->getMemberships()->count(),
            'followercount' => $space->getFollowerCount(),
            'spaceimage'  => $space->getProfileImage()->getUrl(),
            'bannerimage' => $space->getProfileBannerImage()->getUrl(),
            'name' => $space->name,
            'description' => $space->description,
            'ido' => $ido,
            'user'=> $user,
            'ismember' => $ismember,
            's_v' => $space->s_v,
        );
    }

    /**
     * 关注某Space
     *
     * POST /api/space/follow?s=[guid]
     *
     * get.guid : 板块guid
     *
     * @return boolean
     */
    public function actionFollow(){
        $this->forcePostRequest();
        $space = $this->getSpace();
        if (!$space->isMember()) {
            $space->follow();
        }
        return true;
    }

    /**
     * 取消关注某Space
     *
     * POST /api/space/unfollow?s=[guid]
     *
     * get.guid : 板块guid
     *
     * @return boolean
     */
    public function actionUnfollow(){
        $this->forcePostRequest();
        $space = $this->getSpace();
        $space->unfollow();
        return true;
    }

    /**
     * 板块Space被关注的用户列表
     *
     * GET /api/space/follower-list?s=[guid]
     *
     * get.guid : 板块guid
     *
     * @return array guid用户guid, profileimage:头像, displayname:姓名, title:个人Title
     */
    public function actionFollowerList(){
        $query = User::find();
        $query->leftJoin('user_follow', 'user.id=user_follow.user_id and object_model=:userClass and user_follow.object_id=:spaceId', [':userClass' => Space::className(), ':spaceId' => $this->getSpace()->id]);
        $query->orderBy(['user_follow.id' => SORT_DESC]);
        $query->andWhere(['IS NOT', 'user_follow.id', new \yii\db\Expression('NULL')]);
        $query->active();

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid'] = $user->guid;
            $uone['profileimage'] = $user->getProfileImage()->getUrl();
            $uone['displayname'] = $user->displayName;
            $uone['title'] = $user->profile->title;
            $u[] = $uone;
        }
        return $u;
    }
}
?>
